<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :modal-style="{ maxWidth: '520px' }" width="90%" @before-ok="save" @close="reset">
    <a-form ref="formRef" :model="form" auto-label-width>
      <a-form-item label="上级菜单" field="parentId">
        <a-tree-select v-model="form.parentId" placeholder="请选择上级菜单" allow-clear allow-search :data="categoryList"
          :fallback-option="false" :filter-tree-node="filterOptions" />
      </a-form-item>
      <a-form-item label="菜单标题" field="name">
        <a-input v-model.trim="form.name" placeholder="请输入菜单标题" allow-clear />
      </a-form-item>
      <a-form-item label="菜单编码" field="code">
        <a-input v-model.trim="form.code" placeholder="请输入菜单编码" allow-clear />
      </a-form-item>
      <a-form-item label="菜单类型" field="categoryType">
        <a-radio-group v-model="form.categoryType">
          <a-radio :value="0">默认</a-radio>
          <a-radio :value="1">图片</a-radio>
          <a-radio :value="2">图标</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="图片" field="picture">
        <a-upload :custom-request="handleUpload" :default-file-list="fileList" />
      </a-form-item>
      <a-form-item label="跳转链接" field="targetUrl">
        <a-input v-model.trim="form.targetUrl" placeholder="请输入跳转链接" allow-clear />
      </a-form-item>
      <a-form-item label="描述" field="description">
        <a-input v-model.trim="form.description" placeholder="请输入描述" allow-clear />
      </a-form-item>
      <a-form-item label="菜单排序" field="sort">
        <a-input-number v-model="form.sort" placeholder="请输入菜单排序" :min="1" mode="button" style="width: 150px" />
      </a-form-item>
      <a-form-item label="状态" field="status">
        <a-switch v-model="form.status" type="round" :checked-value="1" :unchecked-value="2" checked-text="启用"
          unchecked-text="禁用" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { uploadFile } from '@/apis';
import { addCategory, getCategory, updateCategory } from '@/apis/website';
import { useForm } from '@/hooks';
import { useCategory } from '@/hooks/app';
import { Message, type FormInstance, type RequestOption } from '@arco-design/web-vue';

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { categoryList, getCategoryList } = useCategory()


const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改分类' : '新增分类'))
const formRef = ref<FormInstance>()

const rules: FormInstance['rules'] = {
  parentId: [{ required: true, message: '请选择上级菜单' }],
  name: [{ required: true, message: '请输入分类名称' }],
}


const { form, resetForm } = useForm({
  parentId: 0,
  sort: 999,
  status: 1,
})



// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

const visible = ref(false)

// 新增
const onAdd = (id?: string) => {
  if (!categoryList.value.length) {
    getCategoryList()
  }
  reset()
  form.parentId = id
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const res = await getCategory(id)
  Object.assign(form, res.data)
  visible.value = true
}

// 保存
const save = async () => {

  try {
    //const isInvalid = await formRef.value?.formRef?.validate()
    // console.log('isInvalid:' + isInvalid)
    //if (isInvalid) return false

    if (!form.parentId.length) {
      form.parentId = 0
    }

     //上传的图片
     if (fileList.value.length) {
      form.picture = fileList.value[0].url
    }

    if (isUpdate.value) {
      await updateCategory(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addCategory(form)
      Message.success('新增成功')
    }
    //更新分类数
    // 更新部门树
    await getCategoryList()
    emit('save-success')
    return true
  } catch (error) {
    console.log('error:' + error)
    return false
  }
}

const fileList = ref([] as any)
//上传图片
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController()
    ; (async function requestWrap() {
      const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
      onProgress(20)
      const formData = new FormData()
      formData.append(name as string, fileItem.file as Blob)
      try {
        const res = await uploadFile(formData)
        Message.success('上传成功')
        fileList.value.push({
          uid: '-1',
          name: 'upload1.jpg',
          url: res.data.url
        })
        onSuccess(res)
      } catch (error) {
        onError(error)
      }
    })()
  return {
    abort() {
      controller.abort()
    },
  }
}

defineExpose({ onAdd, onUpdate })
</script>
